<template>
  <div>
    <table>
      <thead>
        <tr>
          <th  v-for="(item,index) in title" :key="index" @click="sortFn(item)">
            {{item.name}}
            <span class="arrow" :class="item.is ? 'asc':'dsc'"></span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item,index) in newData" :key="index">
          <td v-for="(v,i) in item" :key="i">
            {{v}}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  props:["title","data","search"],
  data() {
    return {
      
    };
  },
  methods:{
    sortFn(item){
      if(!item.hasOwnProperty("is")) {
        return;
      }
      item.is = !item.is
      console.log(item);
      if(typeof this.data[0][item.name]=="string"){
        if(item.is) {
          this.data.sort((a,b)=>{
            if(a[item.name].charAt(0)>b[item.name].charAt(0)){
              return 1
            }else if(a[item.name].charAt(0)<b[item.name].charAt(0)) {
              return -1
            }else if(a[item.name].charAt(0)==b[item.name].charAt(0)) {
              return 0
            }
          })
        }else {
          this.data.reverse()
        }
      }else if (typeof this.data[0][item.name]=="number") {
        this.data.sort((a,b)=>{
          return item.is?a[item.name]-b[item.name] : b[item.name]-a[item.name]
        })
      }

    }
  },
  computed:{
    newData() {
      if (!this.search) {
        return this.data
      }else {
        return this.data.filter(v=>{
          return v.name.toUpperCase().indexOf(this.search.toUpperCase()) !=-1
        })
      }
    }
  }
};
</script>

<style scoped>
body {
  font-family: Helvetica Neue, Arial, sans-serif;
  font-size: 14px;
  color: #444;
}

table {
  border: 2px solid #42b983;
  border-radius: 3px;
  background-color: #fff;
}

th {
  background-color: #42b983;
  color: rgba(255, 255, 255, 0.66);
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

td {
  background-color: #f9f9f9;
}

th,
td {
  min-width: 120px;
  padding: 10px 20px;
}

th.active {
  color: #fff;
}

th.active .arrow {
  opacity: 1;
}

.arrow {
  display: inline-block;
  vertical-align: middle;
  width: 0;
  height: 0;
  margin-left: 5px;
  opacity: 0.66;
}

.arrow.asc {
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-bottom: 4px solid #fff;
}

.arrow.dsc {
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 4px solid #fff;
}
</style>